package com.hope.hotel.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hope.hotel.common.Result;
import com.hope.hotel.entity.dto.BookingDTO;
import com.hope.hotel.entity.dto.TravelerDTO;
import com.hope.hotel.entity.po.*;
import com.hope.hotel.entity.vo.BookingDetailVO;
import com.hope.hotel.entity.vo.BookingListVO;
import com.hope.hotel.entity.vo.OrderStatisticsVO;
import com.hope.hotel.entity.vo.RoomTypeStatsVO;
import com.hope.hotel.mapper.*;
import com.hope.hotel.service.BookingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Collectors;

import static java.time.LocalDateTime.now;

/**
 * 预订服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BookingServiceImpl implements BookingService {

    private final BookingMapper bookingMapper;
    private final RoomsMapper roomsMapper;
    private final BookingTravelerMapper bookingTravelerMapper;
    private final BookingVOMapper bookingVOMapper;
    private final MessageMapper messageMapper;

    @Override
    @Transactional
    public Result createBooking(BookingDTO bookingDTO) {
        try {
            // 1. 验证房间是否存在
            Rooms room = roomsMapper.selectById(bookingDTO.getRoomId());
            if (room == null) {
                return Result.error("房间不存在");
            }
            
            if (room.getStatus() != 1) {
                return Result.error("该房间目前不可预订");
            }
            
            // 检查房间容量是否满足入住人数
            if (bookingDTO.getGuestCount() > room.getCapacity()) {
                return Result.error("入住人数超过房间容量");
            }
            
            // 获取入住和退房时间
            LocalDate checkInDate = bookingDTO.getCheckIn();
            LocalDate checkOutDate = bookingDTO.getCheckOut();
            LocalDateTime checkIn = checkInDate.atStartOfDay();
            LocalDateTime checkOut = checkOutDate.atStartOfDay();
            
            long nights = ChronoUnit.DAYS.between(checkInDate, checkOutDate);
            if (nights <= 0) {
                return Result.error("入住日期必须早于退房日期");
            }
            
            // 使用更精确的方法获取指定时间段内最大可预订房间数量
            Integer maxAvailableRooms = bookingMapper.getMaxAvailableRooms(
                bookingDTO.getRoomId(), 
                checkIn, 
                checkOut
            );
            
            // 如果没有查到结果，可能是因为没有预订记录，此时可用数量就是房间总数
            if (maxAvailableRooms == null) {
                maxAvailableRooms = room.getCount();
            }
            
            log.info("房间ID: {}, 入住日期: {}, 退房日期: {}, 最大可预订数量: {}", 
                    bookingDTO.getRoomId(), checkInDate, checkOutDate, maxAvailableRooms);
            
            // 检查是否还有足够的房间
            if (maxAvailableRooms <= 0) {
                return Result.error("所选时间段内该房型已满，请选择其他日期或房型");
            }
            
            // 可选：获取每天的房间可用情况，用于日志或调试
            if (log.isDebugEnabled()) {
                List<Map<String, Object>> dailyAvailability = bookingMapper.getRoomAvailabilityByDateRange(
                    bookingDTO.getRoomId(),
                    checkInDate,
                    checkOutDate.minusDays(1) // 不包括退房当天
                );
                
                log.debug("每日房间可用情况: {}", dailyAvailability);
            }
            
            // 2. 计算总价
            BigDecimal totalPrice = room.getPrice().multiply(BigDecimal.valueOf(nights));
            
            // 验证前端传来的总价是否正确
            if (bookingDTO.getTotalPrice().compareTo(totalPrice) != 0) {
                log.warn("前端计算总价与后端不一致，前端：{}，后端：{}", bookingDTO.getTotalPrice(), totalPrice);
                // 以后端计算为准
            }
            
            // 3. 创建预订记录
            Booking booking = new Booking();
            booking.setUserId(Long.valueOf(bookingDTO.getUserId()));
            booking.setHotelId(Long.valueOf(bookingDTO.getHotelId()));
            booking.setRoomId(bookingDTO.getRoomId().intValue());
            booking.setCheckIn(checkIn);
            booking.setCheckOut(checkOut);
            booking.setGuestCount(bookingDTO.getGuestCount());
            booking.setQuantity(1); // 默认预订一间
            booking.setTotalPrice(totalPrice);
            booking.setStatus("booked"); // 初始状态为已预订
            booking.setRemark(bookingDTO.getRemark());
            booking.setCreatedAt(now());
            booking.setUpdatedAt(now());
            
            // 生成订单编号：当前日期时间 + 4位随机数
            String orderNo = "BK" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(now())
                + String.format("%04d", (int)(Math.random() * 10000));
            booking.setOrderNo(orderNo);
            booking.setPayStatus(0); // 默认未支付
            
            // 保存预订信息
            bookingMapper.insert(booking);
            // 保存入住人信息
            for (TravelerDTO traveler : bookingDTO.getTravelers()) {
                BookingTraveler bookingTraveler = new BookingTraveler();
                bookingTraveler.setBookingId(booking.getBookingId());
                bookingTraveler.setIdCard(traveler.getIdCard());
                bookingTraveler.setPhone(traveler.getPhone());
                bookingTraveler.setName(traveler.getName());
                bookingTravelerMapper.insert(bookingTraveler);
            }

            // 创建一个消息
            Message message = new Message();
            message.setCreateTime(now());
            message.setTitle("订单已创建");
            message.setIsRead(false);
            message.setContent("订单已经创建，请及时支付");
            message.setUserId(String.valueOf(booking.getUserId()));

            messageMapper.insert(message);

            return Result.success(booking.getBookingId(), "预订成功");
        } catch (Exception e) {
            log.error("创建预订失败", e);
            return Result.error("创建预订失败: " + e.getMessage());
        }
    }

    @Override
    public Result getUserBookings(String userId) {
        try {
            // 使用BookingVOMapper获取用户预订列表
            List<BookingListVO> bookings = bookingVOMapper.getUserBookings(Long.valueOf(userId));
            
            // 查询每个预订是否有评价
            for (BookingListVO booking : bookings) {
                Integer reviewCount = bookingVOMapper.countBookingReviews(booking.getBookingId());
                booking.setHasReviewed(reviewCount > 0);
            }
            
            if (bookings == null) {
                bookings = Collections.emptyList();
            }
            
            return Result.success(bookings);
        } catch (Exception e) {
            log.error("获取用户预订列表失败", e);
            return Result.error("获取用户预订列表失败: " + e.getMessage());
        }
    }

    @Override
    public Result getBookingDetail(String bookingId, String userId) {
        try {
            // 先验证预订是否属于该用户
            Integer count = bookingVOMapper.checkBookingBelongsToUser(
                Integer.valueOf(bookingId), 
                Long.valueOf(userId)
            );
            
            if (count == null || count == 0) {
                return Result.error("预订不存在或不属于该用户");
            }
            
            // 查询订单基本信息
            BookingDetailVO bookingDetail = bookingVOMapper.getBookingDetail(Integer.valueOf(bookingId));
            if (bookingDetail == null) {
                return Result.error("预订详情不存在");
            }
            
            // 查询入住人信息
            List<BookingDetailVO.TravelerVO> travelers = bookingVOMapper.getBookingTravelers(Integer.valueOf(bookingId));
            
            if (travelers == null || travelers.isEmpty()) {
                // 如果没有找到入住人信息，添加一个默认的
                BookingDetailVO.TravelerVO defaultTraveler = new BookingDetailVO.TravelerVO();
                defaultTraveler.setName("预订人");
                defaultTraveler.setIdCard("身份证信息未提供");
                travelers = Collections.singletonList(defaultTraveler);
            }
            
            bookingDetail.setTravelers(travelers);
            
            // 查询评价信息
            BookingDetailVO.ReviewVO review = bookingVOMapper.getBookingReview(bookingId);
            if (review != null) {
                bookingDetail.setHasReviewed(true);
                bookingDetail.setReview(review);
            } else {
                bookingDetail.setHasReviewed(false);
            }
            
            return Result.success(bookingDetail);
        } catch (Exception e) {
            log.error("获取预订详情失败", e);
            return Result.error("获取预订详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result cancelBooking(String bookingId, String userId) {
        try {
            // 1. 验证预订是否属于该用户
            Booking booking = bookingMapper.selectById(bookingId);
            if (booking == null) {
                return Result.error("预订不存在");
            }
            if (!booking.getUserId().equals(Long.valueOf(userId))) {
                return Result.error("预订不属于该用户");
            }
            
            // 2. 验证是否可以取消
            if (!"booked".equals(booking.getStatus())) {
                return Result.error("只有已下单的订单才能取消");
            }
            
            // 3. 验证支付状态
            if (booking.getPayStatus() == 1) {
                return Result.error("已支付的订单不能直接取消，请联系客服申请退款");
            }
            
            // 4. 更新预订状态为已取消
            booking.setStatus("cancelled");
            booking.setUpdatedAt(now());
            bookingMapper.updateById(booking);
            
            return Result.success("取消预订成功");
        } catch (Exception e) {
            log.error("取消预订失败", e);
            return Result.error("取消预订失败: " + e.getMessage());
        }
    }

    @Override
    public Result getHotelBookings(String hotelId, int page, int pageSize) {
        try {
            // TODO: 实现获取酒店预订列表的业务逻辑
            // 模拟数据
            return Result.success("获取酒店预订列表成功");
        } catch (Exception e) {
            log.error("获取酒店预订列表失败", e);
            return Result.error("获取酒店预订列表失败: " + e.getMessage());
        }
    }

    // 酒店管理员搜索酒店预订
    @Override
    public Result searchHotelBookings(String hotelId, String keyword, String status, String startDate, String endDate, int page, int pageSize, String adminId) {
        try {
            // 1. 验证管理员权限
            Integer hasPermission = bookingMapper.checkHotelAdminPermission(hotelId, adminId);
            if (hasPermission == null || hasPermission == 0) {
                return Result.error("您没有管理该酒店的权限");
            }
            
            // 2. 创建分页对象
            Page<Map<String, Object>> pageObj = new Page<>(page, pageSize);
            
            // 3. 查询数据
            Page<Map<String, Object>> result = bookingMapper.searchHotelBookings(
                pageObj, hotelId, keyword,
                convertStatusToDb(status), startDate, endDate
            );

            // 4. 处理查询结果
            List<Map<String, Object>> bookings = new ArrayList<>();
            for (Map<String, Object> record : result.getRecords()) {
                Map<String, Object> booking = new HashMap<>();
                booking.put("id", record.get("booking_id"));
                booking.put("orderNo", record.get("order_no"));
                booking.put("customer", record.get("customer_name"));
                booking.put("roomType", record.get("room_type"));

                // 随机选择一个房间号
                Object roomNumbers = record.get("room_numbers");
                try {
                    String randomRoom = getRandomRoom((String) roomNumbers);
                    booking.put("room", randomRoom);
                }catch (Exception e){
                    e.printStackTrace();
                }

                // 处理日期格式
                LocalDateTime checkIn = (LocalDateTime) record.get("check_in");
                LocalDateTime checkOut = (LocalDateTime) record.get("check_out");
                booking.put("checkIn", checkIn.toLocalDate().toString());
                booking.put("checkOut", checkOut.toLocalDate().toString());

                booking.put("guestCount", record.get("guest_count"));
                booking.put("totalPrice", record.get("total_price"));

                // 转换状态
                String dbStatus = (String) record.get("status");
                int payStatus = ((Integer) record.get("pay_status")).intValue();
                booking.put("status", convertStatusToFrontend(dbStatus, payStatus));
                booking.put("payStatus", payStatus == 1);

                // 日期时间格式化
                booking.put("createTime", ((LocalDateTime) record.get("created_at")).toString());
                if (record.get("updated_at") != null) {
                    booking.put("updateTime", ((LocalDateTime) record.get("updated_at")).toString());
                }
                
                bookings.add(booking);
            }
            
            // 5. 组装分页结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("records", bookings);
            resultMap.put("total", result.getTotal());
            resultMap.put("pages", result.getPages());
            resultMap.put("current", result.getCurrent());
            resultMap.put("size", result.getSize());
            
            return Result.success(resultMap);
        } catch (Exception e) {
            log.error("搜索酒店预订失败", e);
            return Result.error("搜索酒店预订失败: " + e.getMessage());
        }
    }

    // 酒店管理员更新订单状态
    @Override
    public Result updateBookingStatus(String bookingId, String status, String adminId) {
        try {
            // 1. 获取预订信息
            Booking booking = bookingMapper.selectById(bookingId);
            if (booking == null) {
                return Result.error("预订不存在");
            }
            
            // 2. 验证管理员权限
            Integer hasPermission = bookingMapper.checkHotelAdminPermission(
                String.valueOf(booking.getHotelId()), adminId
            );
            if (hasPermission == null || hasPermission == 0) {
                return Result.error("您没有管理该酒店的权限");
            }
            
            // 3. 转换状态
            String dbStatus = convertStatusToDb(status);
            if (dbStatus == null) {
                return Result.error("无效的状态值");
            }
            
            // 4. 验证状态变更的合法性
            if (!isValidStatusChange(booking.getStatus(), dbStatus)) {
                return Result.error("无效的状态变更");
            }
            
            // 5. 检查支付状态与状态转换的约束关系
            if ("checked_in".equals(dbStatus) && booking.getPayStatus() == 0) {
                return Result.error("未支付的订单不能办理入住");
            }
            
            if ("cancelled".equals(dbStatus) && booking.getPayStatus() == 1) {
                return Result.error("已支付的订单不能取消，请先退款");
            }
            
            // 6. 更新状态
            booking.setStatus(dbStatus);
            booking.setUpdatedAt(now());
            
            // 7. 如果订单状态为已完成，设置完成时间
            if ("confirmed".equals(dbStatus)) {
                booking.setRemark((booking.getRemark() != null ? booking.getRemark() + " | " : "") 
                        + "完成时间: " + now().toString());
                Message message = new Message();
                message.setTitle("订单" + booking.getOrderNo() + "已确认!!!");
                message.setUserId(String.valueOf(booking.getUserId()));
                message.setIsRead(false);
                message.setContent("您的订单已确认。您可以在\"订单管理\"中查看详细信息，感谢您的支持！");
                message.setCreateTime(now());
                messageMapper.insert(message);
            }

            LambdaUpdateWrapper<Booking> uw = new LambdaUpdateWrapper<>();
            uw.eq(Booking::getBookingId, Long.valueOf(bookingId));
            uw.set(Booking::getStatus, dbStatus);
            uw.set(Booking::getUpdatedAt, now());
            uw.set(Booking::getRemark, booking.getRemark());
            // 8. 保存更新
            bookingMapper.update(uw);
            return Result.success("状态更新成功");
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return Result.error("更新订单状态失败: " + e.getMessage());
        }
    }

    // 获取订单详情(管理员视角)
    @Override
    public Result getBookingDetailForAdmin(String bookingId, String adminId) {
        try {
            // 1. 获取预订信息
            Booking booking = bookingMapper.selectById(bookingId);
            if (booking == null) {
                return Result.error("预订不存在");
            }
            
            // 2. 验证管理员权限
            Integer hasPermission = bookingMapper.checkHotelAdminPermission(
                String.valueOf(booking.getHotelId()), adminId
            );
            if (hasPermission == null || hasPermission == 0) {
                return Result.error("您没有管理该酒店的权限");
            }
            
            // 3. 获取详细信息
            Map<String, Object> detail = bookingMapper.getBookingDetailForAdmin(bookingId);
            if (detail == null) {
                return Result.error("订单详情不存在");
            }
            
            // 处理返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", detail.get("booking_id"));
            result.put("orderNo", detail.get("order_no"));
            result.put("customer", detail.get("customer_name"));
            result.put("phone", detail.get("phone"));

             result.put("hotelName",detail.get("hotel_name"));
            result.put("roomType", detail.get("room_type"));
            result.put("room", detail.get("room_numbers"));

            // 随机选择一个房间号
            Object roomNumbers = detail.get("room_numbers"); // 实体类中是List<String> 储存
            try {
                String randomRoom = getRandomRoom((String) roomNumbers);
                result.put("room", randomRoom);
            }catch (Exception e){
                e.printStackTrace();
            }
            
            // 处理日期格式
            LocalDateTime checkIn = (LocalDateTime) detail.get("check_in");
            LocalDateTime checkOut = (LocalDateTime) detail.get("check_out");
            result.put("checkIn", checkIn.toLocalDate().toString());
            result.put("checkOut", checkOut.toLocalDate().toString());
            
            result.put("guestCount", detail.get("guest_count"));
            result.put("quantity", detail.get("quantity"));
            result.put("totalPrice", detail.get("total_price"));
            
            // 转换状态
            String dbStatus = (String) detail.get("status");
            int payStatus = ((Integer) detail.get("pay_status")).intValue();
            result.put("status", convertStatusToFrontend(dbStatus, payStatus));
            result.put("payStatus", payStatus == 1);
            result.put("remarks", detail.get("remark"));
            
            // 日期时间格式化
            result.put("createTime", ((LocalDateTime) detail.get("created_at")).toString());
            if (detail.get("updated_at") != null) {
                result.put("updateTime", ((LocalDateTime) detail.get("updated_at")).toString());
            }
            
            // 4. 获取入住人信息
            List<Map<String, Object>> travelers = bookingMapper.getBookingTravelers(bookingId);
            
            // 转换结果
            List<Map<String, Object>> travelersList = new ArrayList<>();
            for (Map<String, Object> traveler : travelers) {
                Map<String, Object> travelerMap = new HashMap<>();
                travelerMap.put("id", traveler.get("id"));
                travelerMap.put("name", traveler.get("name"));
                travelerMap.put("idCard", traveler.get("id_card"));
                travelersList.add(travelerMap);
            }
            
            result.put("travelers", travelersList);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败: " + e.getMessage());
        }
    }

    // 随机得到房间号
    public static String getRandomRoom(String roomNumbers) {
        try {
            // 检查输入是否为空或null
            if (roomNumbers == null || roomNumbers.isEmpty()) {
                throw new IllegalArgumentException("房间号字符串不能为空");
            }
            
            // 首先尝试判断是否是JSON数组格式的字符串
            if (roomNumbers.startsWith("[") && roomNumbers.endsWith("]")) {
                // 去掉中括号和引号，提取纯数字部分
                String cleanedNumbers = roomNumbers.replaceAll("[\\[\\]\"]", "");
                if (cleanedNumbers.contains(",")) {
                    // 如果还有逗号，说明是多个房间号
                    String[] rooms = cleanedNumbers.split(",");
                    if (rooms.length > 0) {
                        Random random = new Random();
                        int randomIndex = random.nextInt(rooms.length);
                        return rooms[randomIndex].trim();
                    }
                } else {
                    // 只有一个房间号的情况
                    return cleanedNumbers.trim();
                }
            }
            
            // 如果不是JSON数组格式，按原来的逗号分割处理
            String[] rooms = roomNumbers.split(",");
            
            // 检查是否有房间号
            if (rooms.length == 0) {
                throw new IllegalArgumentException("没有可用的房间号");
            }
            
            // 创建随机数生成器
            Random random = new Random();
            
            // 随机选择一个索引
            int randomIndex = random.nextInt(rooms.length);
            
            // 返回随机选择的房间号
            return rooms[randomIndex].trim();
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时返回一个默认值
            return roomNumbers;
        }
    }
    
    // 更新订单支付状态
    @Override
    public Result updatePayStatus(String bookingId, Integer payStatus, String adminId) {
        try {
            // 1. 获取预订信息
            Booking booking = bookingMapper.selectById(bookingId);
            if (booking == null) {
                return Result.error("预订不存在");
            }
            
            // 2. 验证管理员权限
            Integer hasPermission = bookingMapper.checkHotelAdminPermission(
                String.valueOf(booking.getHotelId()), adminId
            );
            if (hasPermission == null || hasPermission == 0) {
                return Result.error("您没有管理该酒店的权限");
            }
            
            // 3. 验证支付状态参数
            if (payStatus != 0 && payStatus != 1) {
                return Result.error("无效的支付状态值");
            }
            
            // 4. 如果订单已经是取消状态，不允许修改支付状态
            if ("cancelled".equals(booking.getStatus())) {
                return Result.error("已取消的订单不能修改支付状态");
            }
            
            // 5. 更新支付状态
            int rows = bookingMapper.updatePayStatus(bookingId, payStatus);
            if (rows > 0) {
                return Result.success("支付状态更新成功");
            } else {
                return Result.error("支付状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新支付状态失败", e);
            return Result.error("更新支付状态失败: " + e.getMessage());
        }
    }
    
    // 辅助方法：将前端状态转换为数据库状态
    private String convertStatusToDb(String frontendStatus) {
        if (frontendStatus == null) {
            return null;
        }
        
        switch (frontendStatus) {
            case "booked":
                return "booked";
            case "checked_in":
                return "checked_in";
            case "confirmed":
                return "confirmed";
            case "cancelled":
                return "cancelled";
            default:
                return null;
        }
    }
    
    // 辅助方法：将数据库状态转换为前端状态
    private String convertStatusToFrontend(String dbStatus, Integer payStatus) {
        // 直接返回数据库状态，前端直接使用英文状态代码
        return dbStatus;
    }
    
    // 辅助方法：验证状态变更是否合法
    private boolean isValidStatusChange(String currentStatus, String newStatus) {
        // 已取消或已完成的订单不能变更状态
        if ("cancelled".equals(currentStatus) || "confirmed".equals(currentStatus)) {
            return false;
        }
        
        // 订单状态变更规则：
        // 1. booked -> checked_in (只有已支付的booked才能变为checked_in)
        // 2. checked_in -> confirmed (只有checked_in才能变为confirmed)
        // 3. booked -> cancelled (只有未支付的booked才能取消)
        
        if ("cancelled".equals(newStatus)) {
            // 只有未支付的booked状态可以取消
            // 注意：这里只检查了状态，具体是否支付的检查在updateBookingStatus方法中
            return "booked".equals(currentStatus);
        }
        
        if ("booked".equals(currentStatus)) {
            // booked状态只能变为checked_in或cancelled
            return "checked_in".equals(newStatus);
        }
        
        if ("checked_in".equals(currentStatus)) {
            // checked_in状态只能变为confirmed
            return "confirmed".equals(newStatus);
        }
        
        return false;
    }

    @Override
    public Result getHotelBookingStats(String hotelId, String adminId) {
        try {
            // 统计不同状态的订单数量
            Map<String, Integer> statsData = new HashMap<>();
            
            // 所有订单总数
            Integer totalCount = bookingMapper.countBookingsByHotel(Long.valueOf(hotelId));
            statsData.put("total", totalCount != null ? totalCount : 0);
            
            // 已下单订单数量（booked）
            Integer bookedCount = bookingMapper.countBookingsByStatus(Long.valueOf(hotelId), "booked", null);
            statsData.put("booked", bookedCount != null ? bookedCount : 0);
            
            // 已入住订单数量（checked_in）
            Integer checkedInCount = bookingMapper.countBookingsByStatus(Long.valueOf(hotelId), "checked_in", null);
            statsData.put("checked_in", checkedInCount != null ? checkedInCount : 0);
            
            // 已完成订单数量（confirmed - 已退房）
            Integer confirmedCount = bookingMapper.countBookingsByStatus(Long.valueOf(hotelId), "confirmed", null);
            statsData.put("confirmed", confirmedCount != null ? confirmedCount : 0);
            
            // 已取消订单数量（cancelled）
            Integer cancelledCount = bookingMapper.countBookingsByStatus(Long.valueOf(hotelId), "cancelled", null);
            statsData.put("cancelled", cancelledCount != null ? cancelledCount : 0);
            
            return Result.success(statsData);
        } catch (Exception e) {
            log.error("获取酒店订单统计数据失败", e);
            return Result.error("获取酒店订单统计数据失败");
        }
    }

    @Override
    public Result getOrderChartStatistics(String hotelId, String period, String startDate, String endDate, String adminId) {
        try {
            OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
            
            // 处理日期范围
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : LocalDate.now().minusMonths(11);
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : LocalDate.now();
            
            // 根据周期类型查询数据
            if ("month".equals(period)) {
                // 获取月度订单统计数据
                List<Map<String, Object>> monthlyStats = bookingMapper.getMonthlyOrderStats(
                    Long.valueOf(hotelId), start, end);
                
                List<String> dates = new ArrayList<>();
                List<Integer> orderCounts = new ArrayList<>();
                List<Integer> revenue = new ArrayList<>();
                
                // 处理查询结果
                for (Map<String, Object> stat : monthlyStats) {
                    // 使用date_label作为日期标签，它包含年月信息，例如"2023-01"
                    String dateLabel = (String) stat.get("date_label");
                    dates.add(dateLabel);
                    
                    // 获取订单数量和收入金额
                    Long orderCount = (Long) stat.get("order_count");
                    BigDecimal totalRevenue = (BigDecimal) stat.get("total_revenue");
                    
                    orderCounts.add(orderCount != null ? orderCount.intValue() : 0);
                    revenue.add(totalRevenue != null ? totalRevenue.intValue() : 0);
                }
                
                statisticsVO.setDates(dates);
                statisticsVO.setOrderCounts(orderCounts);
                statisticsVO.setRevenue(revenue);
                
            } else if ("quarter".equals(period)) {
                // 获取季度订单统计数据
                List<Map<String, Object>> quarterlyStats = bookingMapper.getQuarterlyOrderStats(
                    Long.valueOf(hotelId), start, end);
                
                List<String> dates = new ArrayList<>();
                List<Integer> orderCounts = new ArrayList<>();
                List<Integer> revenue = new ArrayList<>();
                
                // 处理查询结果
                for (Map<String, Object> stat : quarterlyStats) {
                    String dateLabel = (String) stat.get("date_label");
                    dates.add(dateLabel);
                    
                    Long orderCount = (Long) stat.get("order_count");
                    BigDecimal totalRevenue = (BigDecimal) stat.get("total_revenue");
                    
                    orderCounts.add(orderCount != null ? orderCount.intValue() : 0);
                    revenue.add(totalRevenue != null ? totalRevenue.intValue() : 0);
                }
                
                statisticsVO.setDates(dates);
                statisticsVO.setOrderCounts(orderCounts);
                statisticsVO.setRevenue(revenue);
                
            } else if ("year".equals(period)) {
                // 获取年度订单统计数据
                List<Map<String, Object>> yearlyStats = bookingMapper.getYearlyOrderStats(
                    Long.valueOf(hotelId), start, end);
                
                List<String> dates = new ArrayList<>();
                List<Integer> orderCounts = new ArrayList<>();
                List<Integer> revenue = new ArrayList<>();
                
                // 处理查询结果
                for (Map<String, Object> stat : yearlyStats) {
                    // 年份可能是数字，转为字符串
                    Object yearObj = stat.get("date_label");
                    String year = yearObj != null ? yearObj.toString() : "";
                    dates.add(year);
                    
                    Long orderCount = (Long) stat.get("order_count");
                    BigDecimal totalRevenue = (BigDecimal) stat.get("total_revenue");
                    
                    orderCounts.add(orderCount != null ? orderCount.intValue() : 0);
                    revenue.add(totalRevenue != null ? totalRevenue.intValue() : 0);
                }
                
                statisticsVO.setDates(dates);
                statisticsVO.setOrderCounts(orderCounts);
                statisticsVO.setRevenue(revenue);
                statisticsVO.setYearlyOrderCount(orderCounts);
                statisticsVO.setYearlyRevenue(revenue);
            }
            
            return Result.success(statisticsVO);
            
        } catch (Exception e) {
            log.error("获取订单图表统计数据失败", e);
            return Result.error("获取订单图表统计数据失败");
        }
    }
    
    @Override
    public Result getRoomTypeBookingStats(String hotelId, String adminId) {
        try {
            // 从数据库查询房型订单分布
            List<RoomTypeStatsVO> roomTypeStats = roomsMapper.getRoomTypeBookingStats(Long.valueOf(hotelId));
            
            return Result.success(roomTypeStats);
        } catch (Exception e) {
            log.error("获取房型订单分布统计失败", e);
            return Result.error("获取房型订单分布统计失败");
        }
    }

} 